package cn.wsn2018.tools.util;

import cn.wsn2018.tools.common.CommonValue;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;

/**
 * @author gmz.
 * @date 2018/12/14.
 * @time 19:35
 */
public  class DateUtil {
    public static SimpleDateFormat simpleDateFormat;

    public static String dateToString(Date date){
        simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //统一时区，解决mongodb时间问题
        simpleDateFormat.setCalendar(new GregorianCalendar(new SimpleTimeZone(1000*60*60*8,"GMT")));
        String ctime = simpleDateFormat.format(date);
        return ctime;
    }

    public static Date StringToDate(String dateString){
        simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        simpleDateFormat.setCalendar(new GregorianCalendar(new SimpleTimeZone(1000*60*60*8,"GMT")));
        Date date = null;
        try{
            date = simpleDateFormat.parse(dateString);
        }catch (ParseException e){
            e.printStackTrace();
        }
        return date ;
    }

    /**
     * 判断X时间是否在该合理时间范围内
     * @param fromTime
     * @param toTime
     * @return
     */
    public boolean JudgeTimeRange(String fromTime,String toTime,String time){
        int res1 = time.compareTo(fromTime);
        int res2 = time.compareTo(toTime);
        if(res1 >= 0 && res2 <= 0){
            return true;
        }
        else{
            return false;
        }
    }

//    public static String dateFormateToString(String timeStr,String formatterStr){
//        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatterStr);
//        LocalDate localDate = LocalDate.parse(timeStr, dateTimeFormatter);
//        return localDate.toString().replace("-","/");
//    }

    public static boolean timeOrderCheck(String fromTime,String toTime){
        //时间校验
        LocalDateTime t1 = null;
        LocalDateTime t2 = null;

        try{
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
            if(!StringUtil.isEmptyString(fromTime)){
                t1 = LocalDateTime.parse(fromTime, fmt);
            }

            if(!StringUtil.isEmptyString(toTime)){
                t2 = LocalDateTime.parse(toTime, fmt);
            }

        }catch (DateTimeParseException e){
            //不符合系统时间格式
            System.out.println("65588");
            return false;
        }

        if(t1!=null&&t2!=null){
            //两个时间都不为空时才有意义
            if(!t1.isBefore(t2)){
                //时间顺序输入有问题s
                System.out.println("res:"+!t1.isBefore(t2));
                System.out.println(23);
                return false;
            }
        }

        return true;
    }

}
